package cn.zwx.activiti.example.security;

import cn.hutool.core.util.StrUtil;
import cn.zwx.activiti.example.model.po.UserPO;
import cn.zwx.activiti.example.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Collection;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @description: 用户登录鉴权
 * @projectName:activiti-example
 * @see:cn.zwx.activiti.example.security
 * @author:zhangwenxue
 * @createTime:2021/5/29 10:50
 * @version:1.0
 */
@Component("myUserDetailsService")
public class MyUserDetailsService implements UserDetailsService {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        // 查询用户信息
        UserPO userPO = userService.selectUserByUserName(userName);
        if (Objects.isNull(userPO)){
            throw new UsernameNotFoundException("用户不存在,请联系管理员添加用户信息!!");
        }
        // 转换对象
        UserDetails userDetails = new UserDetails() {
            @Override
            public Collection<? extends GrantedAuthority> getAuthorities() {
                String roles = userPO.getRoles();
               return Arrays.stream(roles.split(",")).map(e->new SimpleGrantedAuthority(e)).collect(Collectors.toSet());
        }
            @Override
            public String getPassword() {
                return userPO.getPassword();
            }
            @Override
            public String getUsername() {
                return userPO.getUserName();
            }

            public String getMobile() {
                return userPO.getMobile();
            }

            @Override
            public boolean isAccountNonExpired() {
                return true;
            }

            @Override
            public boolean isAccountNonLocked() {
                return true;
            }

            @Override
            public boolean isCredentialsNonExpired() {
                return true;
            }

            @Override
            public boolean isEnabled() {
                return true;
            }

        };
        return userDetails;
    }
}
